<?php

declare(strict_types=1);

namespace App\Process;

use App\Model\DevicePublish;
use App\Model\Normal;
use App\Service\MqttClientService;
use App\Utils\Logger;
use Hyperf\Process\AbstractProcess;
use Hyperf\Process\Annotation\Process;

/**
 * @Process(name="MqttPublish")
 */
#[Process(name: 'MqttPublish')]
class MqttPublish extends AbstractProcess
{
    public function handle(): void
    {
        $service = $this->container->get(MqttClientService::class);
        $client = $service->client;
        $logger = $this->container->get(Logger::class);
        $pingTime = time();
        while (true) {
            $publish = DevicePublish::query()->where('is_send', 0)
                ->orderBy('id')->first();
            if ($publish) {
                if(!$publish->topic){
                    $publish->isSend = 1;
                    $publish->save();
                }else{
                    $result = $client->publish($publish->topic, $publish->data, $publish->qos);
                    //if ($result !== true) {
                    $publish->result = $result;
                    $publish->isSend = 1;
                    $publish->save();
                }
                //}
            }
            if (abs($pingTime - time()) > 100) {
                $pingTime = time();
                $client->ping();
            }
        }
    }
}
